﻿using AutoMapper;
using BackData;
using Domain;
using Infratructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using RBAC.API.Command.User;
using RBAC.API.DTOs;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RBAC.API.Handler.User
{
    public class UserGetHandler : IRequestHandler<UserGetCommand, ApiPaging<UserDTO>>
    {
        private readonly IRepository<UserModel> userway;
        private readonly ILogger<UserLoginHandler> log;
        private readonly IMapper mapper;
        private readonly IConfiguration configuration;
        private readonly IRepository<RoleModel> roleway;
        private readonly IRepository<UserRoleModel> userroleway;
        private readonly IHttpContextAccessor httpContextAccessor;

        public UserGetHandler(IRepository<UserModel> userway, ILogger<UserLoginHandler> log,
            IMapper mapper, IConfiguration configuration, IRepository<RoleModel> roleway, IRepository<UserRoleModel> userroleway,
            IHttpContextAccessor httpContextAccessor)
        {
            this.userway = userway;
            this.log = log;
            this.mapper = mapper;
            this.configuration = configuration;
            this.roleway = roleway;
            this.userroleway = userroleway;
            this.httpContextAccessor = httpContextAccessor;
        }
        /// <summary>
        /// 获取用户分页信息
        /// </summary>
        /// <param name="request">参数</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>用户分页查询列表</returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiPaging<UserDTO>> Handle(UserGetCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<UserDTO> res = new ApiPaging<UserDTO>();

            try
            {

                List<UserModel>? user = userway.GetAll().Where(x => x.IsDel == false).ToList();
                foreach (var item in user)
                {
                    item.UserPwd = "******";  //密码不被传输
                }
                if (!string.IsNullOrEmpty(request.UserName))
                {
                    user = user.Where(x => x.UserName.Contains(request.UserName)).ToList();
                }
                List<UserDTO>? value = mapper.Map<List<UserDTO>>(user);
                //获取拼接角色字符串
                foreach (var rolenames in value)
                {
                    //为了测试查看数据ToList
                    var userrole = userroleway.GetAll().Where(x => x.IsDel == false && x.UserId == rolenames.Id);//关于每个用户的角色关系
                    var role = roleway.GetAll().Where(x => x.IsDel == false); //所有角色
                    var link = from ur in userrole join r in role on ur.RoleId equals r.Id select new { ur, r }; //连表中间表和角色表
                    rolenames.RoleName = string.Join(",", link.Select(x => x.r.RoleName)); //分割拼接
                    rolenames.CheckedRoles = string.Join(",",link.Select(x => x.ur.RoleId));

                    //     rolenames.RoleName = string.Join(",", role.Select(x=>x.RoleName)); //分割拼接
                }
                //var link = from u in userway.GetAll().Where(x => x.IsDel == false)
                //           join ur in userroleway.GetAll().Where(x => x.IsDel == false) on u.Id equals ur.UserId
                //            into uur
                //           from ur in uur.DefaultIfEmpty()
                //           join r in roleway.GetAll().Where(x => x.IsDel == false) on ur.RoleId equals r.Id
                //            into urr
                //           from r in urr.DefaultIfEmpty()
                //           select new UserDTO
                //           {
                //               UserName = u.UserName,
                //               UserPwd = u.UserPwd,
                //               UserId = u.Id,
                //               CreateTime = u.CreateTime,
                //               IsUse = u.IsUse,
                //               RoleName = r.RoleName
                //           };
                //foreach (var item in link)
                //{
                //    var k = await GetRole(item.UserId);
                //    item.RoleName = k;
                //}

                //if (!string.IsNullOrEmpty(request.UserName))
                //{
                //    link = link.Where(x => x.UserName.Contains(request.UserName));
                //}
                log.LogInformation($"{DateTime.Now}时{httpContextAccessor.HttpContext?.User.Claims?.FirstOrDefault(x => x.Type == "UserName")?
                    .Value ?? "admin"}成功获取用户分页查询列表");
                res.Totalcount = value.Count();
                res.Message = $"成功获取用户分页查询列表";
                res.Code = StateCode.OK;
                res.PageData = value.OrderBy(x => x.Id).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
                return Task.FromResult(res);
            }


            catch (Exception ex)
            {
                log.LogError($"发生异常{ex.Message}");
                throw;
            }
        }

        //public async Task<string> GetRole(long userId)
        //{
        //    var rolename = userroleway.GetAll().Where(x => x.IsDel == false && x.UserId == userId);  //获取用户对应的多个角色
        //    var str = "";  //角色名变量
        //    foreach (var item in rolename)
        //    {
        //        var key = await roleway.GetValue(item.RoleId);  //拼接变量
        //        str += key.RoleName;
        //    }
        //    return str;
        //}
    }
}
